package de.homeR.client.rest;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import de.homeR.services.HomeRConfigurationService;
import de.homeR.services.domain.PluginMetaInformationCollection;
import de.homeR.services.exceptions.HomeRCommunicationException;
import de.homer.adapter.domain.ConfiguredPlugin;

/**
 * @author André Stannek
 * 
 */
public class HomeRConfigurationClientREST implements HomeRConfigurationService {

	/**
	 * 
	 */
	private String baseURL;

	/**
	 * @param baseURL
	 *            the base URL of the server in http format
	 */
	public HomeRConfigurationClientREST(final String baseURL) {
		this.baseURL = baseURL;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.homeR.services.HomeRConfigurationService#getAllConfiguredPlugins()
	 */
	@Override
	public final List<ConfiguredPlugin> getAllConfiguredPlugins() {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see de.homeR.services.HomeRConfigurationService#getAllPlugins()
	 */
	@Override
	public final PluginMetaInformationCollection getAllPlugins()
			throws HomeRCommunicationException {

		HttpURLConnection connection = null;
		try {
			URL url = new URL(baseURL + "/rest/config/plugins");
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept", "application/xml");
			JAXBContext jc = JAXBContext
					.newInstance(PluginMetaInformationCollection.class);
			return (PluginMetaInformationCollection) jc.createUnmarshaller()
					.unmarshal(connection.getInputStream());
		} catch (IOException | JAXBException e) {
			throw new HomeRCommunicationException(e);
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}
}
